﻿using System;
using COFE.Core;
using COFE.Core.Logger;

namespace COFE.Data
{
    /// <summary>
    /// Listen to COFEShared.FileSystemEventDispatcher and modify database entries accordingly.
    /// </summary>
    public class DBFileSystemEventListener : IEventListener<FileSystemEventArgsExA>
    {
        #region Constructor

        #endregion

        #region Methods

        public void DispatchEvent(object sender, FileSystemEventArgsExA args)
        {
            switch (args.ChangeType)
            {
                case ModifiedAction.Created: NotifyCreated(sender, args); break;
                case ModifiedAction.Changed: NotifyChanged(sender, args); break;
                case ModifiedAction.Deleted: NotifyDeleted(sender, args); break;
                case ModifiedAction.Renamed:
                    if (args is RenameEventArgsExA)
                        NotifyRenamed(sender, args as RenameEventArgsExA); break;
            }
        }

        public void NotifyChanged(object sender, FileSystemEventArgsExA args)
        {            
            COFEDBShared.DBEntryManager.ExpireEntry(args.ParsePath, true, true);
        }

        public void NotifyCreated(object sender, FileSystemEventArgsExA args)
        {
            string parentParsePath = COFEPath.GetDirectoryName(args.ParsePath);
            if (!String.IsNullOrEmpty(parentParsePath))
                COFEDBShared.DBEntryManager.ExpireEntry(parentParsePath, false, true);            
        }

        public void NotifyDeleted(object sender, FileSystemEventArgsExA args)
        {
            COFEDBShared.DBEntryManager.RemoveEntry(args.ParsePath);
        }

        public void NotifyRenamed(object sender, RenameEventArgsExA args)
        {
            COFEDBShared.DBEntryManager.RemoveEntry(args.ParsePath);
        }

        #endregion

        #region Data

        #endregion

        #region Public Properties

        public string[] ListenPatterns { get { return new string[] { }; } }
        public string[] ListenListers { get { return new string[] { }; } }

        #endregion


    }
}
